package com.example.auth.config;

import com.example.auth.entity.User;
import com.example.auth.service.IMenuService;
import com.example.auth.service.IUserService;
import com.example.common.constant.LoginConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
/**
 * 在oauth2.0中添加额外的信息
 */
@Component
public class AddionInfo  implements TokenEnhancer {
    private Logger logger = LoggerFactory.getLogger(AddionInfo.class);
    @Autowired
    private IUserService userService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication oAuth2Authentication) {
        Map<String,Object> info = accessToken.getAdditionalInformation();
        //获取认证的凭证
         Object principal  = oAuth2Authentication.getPrincipal();
         logger.info("principal:{}",principal);
         if (!(principal instanceof  String)  && null!=principal){
             UserDetails userDetails = (UserDetails)principal;
            String username = userDetails.getUsername();
            User user = userService.findByUserName(username);
            if (null!= user){
              List<String> pemissList =  menuService.findPermissByUid(user.getId());
              //保存访问接口权限，限制访问服务的接口
              redisTemplate.opsForValue().set(LoginConstant.LONGIN_PERURLS+username,pemissList);
              logger.info("保存菜单...");
              //保存菜单路径
              info.put("per_urls",pemissList);
              //查询权限信息
              logger.info("permissList:{}",pemissList);
            }
         }
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }
}
